---
title: API Reference
i18nReady: true
---
import Since from '~/components/Since.astro';
import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro';
import ReadMore from '~/components/ReadMore.astro';

## `Astro` global

The `Astro` global is available in all contexts in `.astro` files. It has the following functions:

### `Astro.glob()`

`Astro.glob()` is a way to load many local files into your static site setup.

```astro
---
// src/components/my-component.astro
const posts = await Astro.glob('../pages/post/*.md'); // returns an array of posts that live at ./src/pages/post/*.md
---

<div>
{posts.slice(0, 3).map((post) => (
  <article>
    <h2>{post.frontmatter.title}</h2>
    <p>{post.frontmatter.description}</p>
    <a href={post.url}>Read more</a>
  </article>
))}
</div>
```

`.glob()` only takes one parameter: a relative URL glob of which local files you'd like to import. It’s asynchronous, and returns an array of the exports from matching files.

`.glob()` can't take variables or strings that interpolate them, as they aren't statically analyzable. (See [the troubleshooting guide](/en/guides/troubleshooting/#supported-values) for a workaround.) This is because `Astro.glob()` is a wrapper of Vite's [`import.meta.glob()`](https://vitejs.dev/guide/features.html#glob-import).

:::note
You can also use `import.meta.glob()` itself in your Astro project. You may want to do this when:
- You need this feature in a file that isn't `.astro`, like an API route. `Astro.glob()` is only available in `.astro` files, while `import.meta.glob()` is available anywhere in the project.
- You don't want to load each file immediately. `import.meta.glob()` can return functions that import the file content, rather than returning the content itself. Note that this import includes all styles and scripts for any imported files. These will be bundled and added to the page whether or not a file is actually used, as this is decided by static analysis, not at runtime.
- You want access to each file's path. `import.meta.glob()` returns a map of a file's path to its content, while `Astro.glob()` returns a list of content.
- You want to pass multiple patterns; for example, you want to add a "negative pattern" that filters out certain files. `import.meta.glob()` can optionally take an array of glob strings, rather than a single string.

Read more in the [Vite documentation](https://vitejs.dev/guide/features.html#glob-import).
:::
#### Markdown Files

Markdown files have the following interface:

```ts
export interface MarkdownInstance<T extends Record<string, any>> {
  /* Any data specified in this file's YAML frontmatter */
	frontmatter: T;
  /* The file path of this file */
	file: string;
  /* The rendered path of this file */
	url: string | undefined;
  /* Astro Component that renders the contents of this file */
	Content: AstroComponent;
  /* Function that returns an array of the h1...h6 elements in this file */
	getHeadings(): Promise<{ depth: number; slug: string; text: string }[]>;
}
```

You can optionally provide a type for the `frontmatter` variable using a TypeScript generic.

```astro
---
interface Frontmatter {
  title: string;
  description?: string;
}
const posts = await Astro.glob<Frontmatter>('../pages/post/*.md');
---

<ul>
  {posts.map(post => <li>{post.frontmatter.title}</li>)}
</ul>
```

#### Astro Files

Astro files have the following interface:

```ts
export interface AstroInstance {
  /* The file path of this file */
  file: string;
  /* The URL for this file (if it is in the pages directory) */
	url: string | undefined;
	default: AstroComponent;
}
```

#### Other Files

Other files may have various different interfaces, but `Astro.glob()` accepts a TypeScript generic if you know exactly what an unrecognized file type contains.

```ts
---
interface CustomDataFile {
  default: Record<string, any>;
}
const data = await Astro.glob<CustomDataFile>('../data/**/*.js');
---
```

### `Astro.props`

`Astro.props` is an object containing any values that have been passed as [component attributes](/en/basics/astro-components/#component-props). Layout components for `.md` and `.mdx` files receive frontmatter values as props.

```astro {3}
---
// src/components/Heading.astro
const { title, date } = Astro.props;
---
<div>
  <h1>{title}</h1>
  <p>{date}</p>
</div>
```

```astro /title=".+"/ /date=".+"/
---
// src/pages/index.astro
import Heading from '../components/Heading.astro';
---
<Heading title="My First Post" date="09 Aug 2022" />
```

<ReadMore>Learn more about how [Markdown and MDX Layouts](/en/guides/markdown-content/#frontmatter-layout) handle props.</ReadMore>

<ReadMore>Learn how to add [TypeScript type definitions for your props](/en/guides/typescript/#component-props).</ReadMore>

### `Astro.params`

`Astro.params` is an object containing the values of dynamic route segments matched for this request.

In static builds, this will be the `params` returned by `getStaticPaths()` used for prerendering [dynamic routes](/en/guides/routing/#dynamic-routes).

In SSR builds, this can be any value matching the path segments in the dynamic route pattern.

```astro title="src/pages/posts/[id].astro"
---
export function getStaticPaths() {
  return [
    { params: { id: '1' } },
    { params: { id: '2' } },
    { params: { id: '3' } }
  ];
}

const { id } = Astro.params;
---
<h1>{id}</h1>
```

See also: [`params`](#params)

### `Astro.request`

`Astro.request` is a standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object. It can be used to get the `url`, `headers`, `method`, and even body of the request. 

```astro
<p>Received a {Astro.request.method} request to "{Astro.request.url}".</p>
<p>Received request headers: <code>{JSON.stringify(Object.fromEntries(Astro.request.headers))}</code>
```

See also: [`Astro.url`](#astrourl)

:::note
With the default `output: 'static'` option, `Astro.request.url` does not contain search parameters, like `?foo=bar`, as it's not possible to determine them ahead of time during static builds. However in `output: 'server'` mode, `Astro.request.url` does contain search parameters as it can be determined from a server request.
:::

### `Astro.response`


`Astro.response` is a standard `ResponseInit` object. It has the following structure. 

 - `status`: The numeric status code of the response, e.g., `200`.
 - `statusText`: The status message associated with the status code, e.g., `'OK'`.
 - `headers`: A [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers) instance that you can use to set the HTTP headers of the response.

`Astro.response` is used to set the `status`, `statusText`, and `headers` for a page's response.


```astro
---
if(condition) {
  Astro.response.status = 404;
  Astro.response.statusText = 'Not found';
}
---
```

Or to set a header:

```astro
---
Astro.response.headers.set('Set-Cookie', 'a=b; Path=/;');
---
```

### `Astro.cookies`

<p><Since v="1.4.0" /></p>

`Astro.cookies` contains utilities for reading and manipulating cookies in [server-side rendering](/en/guides/server-side-rendering/) mode.

##### `get`

<p>
**Type:** `(key: string, options?: CookieGetOptions) => AstroCookie`
</p>

Gets the cookie as an [`AstroCookie`](#astrocookie) object, which contains the `value` and utility functions for converting the cookie to non-string types.

##### `has`

<p>
**Type:** `(key: string) => boolean`
</p>

Whether this cookie exists. If the cookie has been set via `Astro.cookies.set()` this will return true, otherwise it will check cookies in the `Astro.request`.

##### `set`

<p>
**Type:** `(key: string, value: string | number | boolean | object, options?: CookieSetOptions) => void`
</p>

Sets the cookie `key` to the given value. This will attempt to convert the cookie value to a string. Options provide ways to set [cookie features](https://www.npmjs.com/package/cookie#options-1), such as the `maxAge` or `httpOnly`.

##### `delete`

<p>
**Type:** `(key: string, options?: CookieDeleteOptions) => void`
</p>

Marks the cookie as deleted. Once a cookie is deleted `Astro.cookies.has()` will return `false` and `Astro.cookies.get()` will return an [`AstroCookie`](#astrocookie) with a `value` of `undefined`. Options allow setting the `domain` and `path` of the cookie to delete.

##### `headers`

<p>
**Type:** `() => Iterator<string>`
</p>

Gets the header values for `Set-Cookie` that will be sent out with the response.

#### `AstroCookie`

Getting a cookie via `Astro.cookies.get()` returns a `AstroCookie` type. It has the following structure.

##### `value`

<p>
**Type:** `string | undefined`
</p>

The raw string value of the cookie.

##### `json`

<p>
**Type:** `() => Record<string, any>`
</p>

Parses the cookie value via `JSON.parse()`, returning an object. Throws if the cookie value is not valid JSON.

##### `number`

<p>
**Type:** `() => number`
</p>

Parses the cookie value as a Number. Returns NaN if not a valid number.

##### `boolean`

<p>
**Type:** `() => boolean`
</p>

Converts the cookie value to a boolean.

#### `CookieGetOptions`

<p><Since v="4.1.0"/></p>

Getting a cookie also allows specifying options via the `CookieGetOptions` interface:

##### `decode`

<p>
**Type:** `(value: string) => string`
</p>

Allows customization of how a cookie is deserialized into a value.

#### `CookieSetOptions`

<p><Since v="4.1.0"/></p>

Setting a cookie via `Astro.cookies.set()` allows passing in a `CookieSetOptions` to customize how the cookie is serialized.

##### `domain`

<p>
**Type:** `string`
</p>

 Specifies the domain. If no domain is set, most clients will interpret to apply to the current domain.

 ##### `expires`

 <p>
 **Type:** `Date`
 </p>

Specifies the date on which the cookie will expire.

##### `httpOnly`

<p>
**Type:** `boolean`
</p>

If true, the cookie will not be accessible client-side.

##### `maxAge`

<p>
**Type:** `number`
</p>

Specifies a number, in seconds, for which the cookie is valid.

##### `path`

<p>
**Type:** `string`
</p>

Specifies a subpath of the domain in which the cookie is applied.

##### `sameSite`

<p>
**Type:** `boolean | 'lax' | 'none' | 'strict'`
</p>

Specifies the value of the [SameSite](https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7) cookie header.

##### `secure`

<p>
**Type:** `boolean`
</p>

If true, the cookie is only set on https sites.

##### `encode`

<p>
**Type:** `(value: string) => string`
</p>

Allows customizing how the cookie is serialized.

### `Astro.redirect()`
`Astro.redirect()` allows you to redirect to another page. 
A page (and not a child component) must `return` the result of `Astro.redirect()` for the redirect to occur.

```astro title="src/pages/account.astro" {8}
---
import { isLoggedIn } from '../utils';

const cookie = Astro.request.headers.get('cookie');

// If the user is not logged in, redirect them to the login page
if (!isLoggedIn(cookie)) {
  return Astro.redirect('/login');
}
---
```

### `Astro.canonicalURL`

:::caution[Deprecated]
Use [`Astro.url`](#astrourl) to construct your own canonical URL. 
:::

The [canonical URL][canonical] of the current page.

### `Astro.url`

<p><Since v="1.0.0-rc" /></p>

A [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) object constructed from the current `Astro.request.url` URL string value. Useful for interacting with individual properties of the request URL, like pathname and origin. 

Equivalent to doing `new URL(Astro.request.url)`. 

```astro
<h1>The current URL is: {Astro.url}</h1>
<h1>The current URL pathname is: {Astro.url.pathname}</h1>
<h1>The current URL origin is: {Astro.url.origin}</h1>
```

You can also use `Astro.url` to create new URLs by passing it as an argument to [`new URL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL).

```astro title="src/pages/index.astro"
---
// Example: Construct a canonical URL using your production domain
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
// Example: Construct a URL for SEO meta tags using your current domain
const socialImageURL = new URL('/images/preview.png', Astro.url);
---
<link rel="canonical" href={canonicalURL} />
<meta property="og:image" content={socialImageURL} />
```

### `Astro.clientAddress`

<p><Since v="1.0.0-rc" /></p>

Specifies the [IP address](https://en.wikipedia.org/wiki/IP_address) of the request. This property is only available when building for SSR (server-side rendering) and should not be used for static sites.

```astro
---
const ip = Astro.clientAddress;
---

<div>Your IP address is: <span class="address">{ ip }</span></div>
```

### `Astro.site`

`Astro.site` returns a `URL` made from `site` in your Astro config. If `site` in your Astro config isn't defined, `Astro.site` won't be defined.

### `Astro.generator`

<p><Since v="1.0.0" /></p>

`Astro.generator` is a convenient way to add a [`<meta name="generator">`](https://html.spec.whatwg.org/multipage/semantics.html#meta-generator) tag with your current version of Astro. It follows the format `"Astro v1.x.x"`.

```astro mark="Astro.generator"
<html>
  <head>
    <meta name="generator" content={Astro.generator} />
  </head>
  <body>
    <footer>
      <p>Built with <a href="https://astro.build">{Astro.generator}</a></p>
    </footer>
  </body>
</html>
```

### `Astro.slots`

`Astro.slots` contains utility functions for modifying an Astro component's slotted children.

#### `Astro.slots.has()`

**Type:** `(slotName: string) => boolean`

You can check whether content for a specific slot name exists with `Astro.slots.has()`. This can be useful when you want to wrap slot contents, but only want to render the wrapper elements when the slot is being used.

```astro  title="src/pages/index.astro"
---
---
<slot />

{Astro.slots.has('more') && (
  <aside>
    <h2>More</h2>
    <slot name="more" />
  </aside>
)}
```

#### `Astro.slots.render()`

**Type:** `(slotName: string, args?: any[]) => Promise<string>`

You can asynchronously render the contents of a slot to a string of HTML using `Astro.slots.render()`.

```astro
---
const html = await Astro.slots.render('default');
---
<Fragment set:html={html} />
```

:::note
This is for advanced use cases! In most circumstances, it is simpler to render slot contents with [the `<slot />` element](/en/basics/astro-components/#slots).
:::

`Astro.slots.render()` optionally accepts a second argument: an array of parameters that will be forwarded to any function children. This can be useful for custom utility components.

For example, this `<Shout />` component converts its `message` prop to uppercase and passes it to the default slot:

```astro title="src/components/Shout.astro" "await Astro.slots.render('default', [message])"
---
const message = Astro.props.message.toUpperCase();
let html = '';
if (Astro.slots.has('default')) {
  html = await Astro.slots.render('default', [message]);
}
---
<Fragment set:html={html} />
```

A callback function passed as `<Shout />`’s child will receive the all-caps `message` parameter:

```astro title="src/pages/index.astro"
---
import Shout from "../components/Shout.astro";
---
<Shout message="slots!">
  {(message) => <div>{message}</div>}
</Shout>

<!-- renders as <div>SLOTS!</div> -->
```

### `Astro.self`

`Astro.self` allows Astro components to be recursively called. This behaviour lets you render an Astro component from within itself by using `<Astro.self>` in the component template. This can be helpful for iterating over large data stores and nested data-structures.

```astro
---
// NestedList.astro
const { items } = Astro.props;
---
<ul class="nested-list">
  {items.map((item) => (
    <li>
      <!-- If there is a nested data-structure we render `<Astro.self>` -->
      <!-- and can pass props through with the recursive call -->
      {Array.isArray(item) ? (
        <Astro.self items={item} />
      ) : (
        item
      )}
    </li>
  ))}
</ul>
```

This component could then be used like this:

```astro
---
import NestedList from './NestedList.astro';
---
<NestedList items={['A', ['B', 'C'], 'D']} />
```

And would render HTML like this:

```html
<ul class="nested-list">
  <li>A</li>
  <li>
    <ul class="nested-list">
      <li>B</li>
      <li>C</li>
    </ul>
  </li>
  <li>D</li>
</ul>
```


### `Astro.locals`

`Astro.locals` is an object containing any values from the [`context.locals`](#contextlocals) object from a middleware. Use this to access data returned by middleware in your `.astro` files.

```astro title="src/pages/Orders.astro"
---
const title = Astro.locals.welcomeTitle();
const orders = Array.from(Astro.locals.orders.entries());
---
<h1>{title}</h1>
<ul>
    {orders.map(order => {
        return <li>{/* do something with each order */}</li>
    })}
</ul>
```

### `Astro.preferredLocale`

`Astro.preferredLocale` is a computed value that represents the preferred locale of the user. 

It is computed by checking the configured locales in your `i18n.locales` array and locales supported by the users's browser via the header `Accept-Language`. This value is `undefined` if no such match exists.

This property is only available when building for SSR (server-side rendering) and should not be used for static sites.

### `Astro.preferredLocaleList`

`Astro.preferredLocaleList` represents the array of all locales that are both requested by the browser and supported by your website. This produces a list of all compatible languages between your site and your visitor. 

If none of the browser's requested languages are found in your locales array, then the value is `[]`: you do not support any of your visitor's preferred locales.

If the browser does not specify any preferred languages, then this value will be [`i18n.locales`](/en/reference/configuration-reference/#i18nlocales): all of your supported locales will be considered equally preferred by a visitor with no preferences. 

This property is only available when building for SSR (server-side rendering) and should not be used for static sites.

### `Astro.currentLocale`

The locale computed from the current URL, using the syntax specified in your `locales` configuration. If the URL does not contain a `/[locale]/` prefix, then the value will default to `i18n.defaultLocale`.

## Endpoint Context

[Endpoint functions](/en/guides/endpoints/) receive a context object as the first parameter. It mirrors many of the `Astro` global properties.

```ts title="endpoint.json.ts"
import type { APIContext } from 'astro';

export function GET(context: APIContext) {
  // ...
}
```

### `context.params`

`context.params` is an object containing the values of dynamic route segments matched for this request.

In static builds, this will be the `params` returned by `getStaticPaths()` used for prerendering [dynamic routes](/en/guides/routing/#dynamic-routes).

In SSR builds, this can be any value matching the path segments in the dynamic route pattern.

```ts title="src/pages/posts/[id].json.ts"
import type { APIContext } from 'astro';

export function getStaticPaths() {
  return [
    { params: { id: '1' } },
    { params: { id: '2' } },
    { params: { id: '3' } }
  ];
}

export function GET({ params }: APIContext) {
	return new Response(
    JSON.stringify({ id: params.id }),
  );
}
```

See also: [`params`](#params)

### `context.props`

`context.props` is an object containing any `props` passed from `getStaticPaths()`. Because `getStaticPaths()` is not used when building for SSR (server-side rendering), `context.props` is only available in static builds.

```ts title="src/pages/posts/[id].json.ts"
import type { APIContext } from 'astro';

export function getStaticPaths() {
  return [
    { params: { id: '1' }, props: { author: 'Blu' } },
    { params: { id: '2' }, props: { author: 'Erika' } },
    { params: { id: '3' }, props: { author: 'Matthew' } }
  ];
}

export function GET({ props }: APIContext) {
	return new Response(
    JSON.stringify({ author: props.author }),
  );
}
```

See also: [Data Passing with `props`](#data-passing-with-props)

### `context.request`

A standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object. It can be used to get the `url`, `headers`, `method`, and even body of the request.

```ts
import type { APIContext } from 'astro';

export function GET({ request }: APIContext) {
  return new Response(`Hello ${request.url}`);
}
```

See also: [Astro.request](#astrorequest)

### `context.cookies`

`context.cookies` contains utilities for reading and manipulating cookies.

See also: [Astro.cookies](#astrocookies)

### `context.url`

A [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) object constructed from the current `context.request.url` URL string value.

See also: [Astro.url](#astrourl)

### `context.clientAddress`

Specifies the [IP address](https://en.wikipedia.org/wiki/IP_address) of the request. This property is only available when building for SSR (server-side rendering) and should not be used for static sites.

```ts
import type { APIContext } from 'astro';

export function GET({ clientAddress }: APIContext) {
  return new Response(`Your IP address is: ${clientAddress}`);
}
```

See also: [Astro.clientAddress](#astroclientaddress)


### `context.site`

`context.site` returns a `URL` made from `site` in your Astro config. If undefined, this will return a URL generated from `localhost`.

See also: [Astro.site](#astrosite)

### `context.generator`

`context.generator` is a convenient way to indicate the version of Astro your project is running. It follows the format `"Astro v1.x.x"`.

```ts title="src/pages/site-info.json.ts"
import type { APIContext } from 'astro';

export function GET({ generator, site }: APIContext) {
  const body = JSON.stringify({ generator, site });
  return new Response(body);
}
```

See also: [Astro.generator](#astrogenerator)

### `context.redirect()`

`context.redirect()` returns a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) object that allows you to redirect to another page. This function is only available when building for SSR (server-side rendering) and should not be used for static sites.

```ts
import type { APIContext } from 'astro';

export function GET({ redirect }: APIContext) {
  return redirect('/login', 302);
}
```

See also: [`Astro.redirect()`](#astroredirect)

### `context.locals`

`context.locals` is an object used to store and access arbitrary information during the lifecycle of a request.

Middleware functions can read and write the values of `context.locals`:

```ts title="src/middleware.ts"
import type { MiddlewareHandler } from 'astro';

export const onRequest: MiddlewareHandler = ({ locals }, next) => {
  if (!locals.title) {
    locals.title = "Default Title";
  }
  return next();
}
```

API endpoints can only read information from `context.locals`:

```ts title="src/pages/hello.ts"
import type { APIContext } from 'astro';

export function GET({ locals }: APIContext) {
  return new Response(locals.title); // "Default Title"
}
```

See also: [`Astro.locals`](#astrolocals)

## `getStaticPaths()`

If a page uses dynamic params in the filename, that component will need to export a `getStaticPaths()` function.

This function is required because Astro is a static site builder. That means that your entire site is built ahead of time. If Astro doesn't know to generate a page at build time, your users won't see it when they visit your site.

```astro
---
export async function getStaticPaths() {
  return [
    { params: { /* required */ }, props: { /* optional */ } },
    { params: { ... } },
    { params: { ... } },
    // ...
  ];
}
---
<!-- Your HTML template here. -->
```

The `getStaticPaths()` function should return an array of objects to determine which paths will be pre-rendered by Astro.

It can also be used in static file endpoints for [dynamic routing](/en/guides/endpoints/#params-and-dynamic-routing).

:::caution
The `getStaticPaths()` function executes in its own isolated scope once, before any page loads. Therefore you can't reference anything from its parent scope, other than file imports. The compiler will warn if you break this requirement.
:::

### `params`

The `params` key of every returned object tells Astro what routes to build. The returned params must map back to the dynamic parameters and rest parameters defined in your component filepath.

`params` are encoded into the URL, so only strings are supported as values. The value for each `params` object must match the parameters used in the page name.

For example, suppose that you have a page at `src/pages/posts/[id].astro`. If you export `getStaticPaths` from this page and return the following for paths:

```astro
---
export async function getStaticPaths() {
  return [
    { params: { id: '1' } },
    { params: { id: '2' } },
    { params: { id: '3' } }
  ];
}

const { id } = Astro.params;
---
<h1>{id}</h1>
```

Then Astro will statically generate `posts/1`, `posts/2`, and `posts/3` at build time.

### Data Passing with `props`

To pass additional data to each generated page, you can also set a `props` value on every returned path object. Unlike `params`, `props` are not encoded into the URL and so aren't limited to only strings.

For example, suppose that you generate pages based off of data fetched from a remote API. You can pass the full data object to the page component inside of `getStaticPaths`:

```astro
---
export async function getStaticPaths() {
  const data = await fetch('...').then(response => response.json());

  return data.map((post) => {
    return {
      params: { id: post.id },
      props: { post },
    };
  });
}

const { id } = Astro.params;
const { post } = Astro.props;
---
<h1>{id}: {post.name}</h1>
```

You can also pass a regular array, which may be helpful when generating or stubbing a known list of routes.

```astro
---
export async function getStaticPaths() {
  const posts = [
    {id: '1', category: "astro", title: "API Reference"},
    {id: '2', category: "react", title: "Creating a React Counter!"}
  ];
  return posts.map((post) => {
    return {
      params: { id: post.id },
      props: { post }
    };
  });
}
const {id} = Astro.params;
const {post} = Astro.props;
---
<body>
  <h1>{id}: {post.title}</h1>
  <h2>Category: {post.category}</h2>
</body>
```

Then Astro will statically generate `posts/1` and `posts/2` at build time using the page component in `pages/posts/[id].astro`. The page can reference this data using `Astro.props`:

### `paginate()`

Pagination is a common use-case for websites that Astro natively supports via the `paginate()` function. `paginate()` will automatically generate the array to return from `getStaticPaths()` that creates one URL for every page of the paginated collection. The page number will be passed as a param, and the page data will be passed as a `page` prop.

```js
export async function getStaticPaths({ paginate }) {
  // Load your data with fetch(), Astro.glob(), etc.
  const response = await fetch(`https://pokeapi.co/api/v2/pokemon?limit=150`);
  const result = await response.json();
  const allPokemon = result.results;

  // Return a paginated collection of paths for all posts
  return paginate(allPokemon, { pageSize: 10 });
}

// If set up correctly, The page prop now has everything that
// you need to render a single page (see next section).
const { page } = Astro.props;
```

`paginate()` assumes a file name of `[page].astro` or `[...page].astro`. The `page` param becomes the page number in your URL:

- `/posts/[page].astro` would generate the URLs `/posts/1`, `/posts/2`, `/posts/3`, etc.
- `/posts/[...page].astro` would generate the URLs `/posts`, `/posts/2`, `/posts/3`, etc.

`paginate()` has the following arguments:
- `pageSize` - The number of items shown per page
- `params` - Send additional parameters for creating dynamic routes
- `props` - Send additional props to be available on each page

#### The pagination `page` prop

Pagination will pass a `page` prop to every rendered page that represents a single page of data in the paginated collection. This includes the data that you've paginated (`page.data`) as well as metadata for the page (`page.url`, `page.start`, `page.end`, `page.total`, etc). This metadata is useful for things like a "Next Page" button or a "Showing 1-10 of 100" message.

##### `page.data`

<p>
**Type:** `Array`
</p>

Array of data returned from `data()` for the current page.

##### `page.start`

<p>
**Type:** `number`
</p>

Index of first item on current page, starting at `0`. (e.g. if `pageSize: 25`, this would be `0` on page 1, `25` on page 2, etc.)

##### `page.end`

<p>
**Type:** `number`
</p>

Index of last item on current page.

##### `page.size`

<p>
**Type:** `number`
</p>

How many items per-page.

##### `page.total`

<p>
**Type:** `number`
</p>

The total number of items across all pages.

##### `page.currentPage`

<p>
**Type:** `number`
</p>

The current page number, starting with `1`.

##### `page.lastPage`

<p>
**Type:** `number`
</p>

The total number of pages.

##### `page.url.current`

<p>
**Type:** `string`
</p>

Get the URL of the current page (useful for canonical URLs).

##### `page.url.prev`

<p>
**Type:** `string | undefined`
</p>

Get the URL of the previous page (will be `undefined` if on page 1).

##### `page.url.next`

<p>
**Type:** `string | undefined`
</p>

Get the URL of the next page (will be `undefined` if no more pages).

## `import.meta`

All ESM modules include a `import.meta` property. Astro adds `import.meta.env` through [Vite](https://vitejs.dev/guide/env-and-mode.html).

**`import.meta.env.SSR`** can be used to know when rendering on the server. Sometimes you might want different logic, like a component that should only be rendered in the client:

```jsx
export default function () {
  return import.meta.env.SSR ? <div class="spinner"></div> : <FancyComponent />;
}
```

## Images (`astro:assets`)

### `getImage()`

:::caution
`getImage()` relies on server-only APIs and breaks the build when used on the client.
:::

The `getImage()` function is intended for generating images destined to be used somewhere else than directly in HTML, for example in an [API Route](/en/guides/endpoints/#server-endpoints-api-routes). It also allows you to create your own custom `<Image />` component.

`getImage()` takes an options object with the [same properties as the Image component](#properties) (except `alt`).

```astro
---
import { getImage } from "astro:assets";
import myBackground from "../background.png"

const optimizedBackground = await getImage({src: myBackground, format: 'avif'})
---

<div style={`background-image: url(${optimizedBackground.src});`}></div>
```

It returns an object with the following properties:

```js
{
  options: {...} // Original parameters passed
  src: "https//..." // Path to the generated image
  attributes: {...} // Additional HTML attributes needed to render the image (width, height, style, etc..)
}
```

## Content Collections (`astro:content`)

<p><Since v="2.0.0" /></p>

Content collections offer APIs to configure and query your Markdown or MDX documents in `src/content/`. For features and usage examples, [see our content collections guide](/en/guides/content-collections/).

### `defineCollection()`

`defineCollection()` is a utility to configure a collection in a `src/content/config.*` file.

```ts
// src/content/config.ts
import { z, defineCollection } from 'astro:content';
const blog = defineCollection({
  type: 'content',
  schema: z.object({
    title: z.string(),
    permalink: z.string().optional(),
  }),
});

// Expose your defined collection to Astro
// with the `collections` export
export const collections = { blog };
```

This function accepts the following properties:

#### `type`

<p><Since v="2.5.0" /></p>

**Type:** `'content' | 'data'`  
**Default:** `'content'`

`type` is a string that defines the type of entries stored within a collection:

- `'content'` - for content-authoring formats like Markdown (`.md`), MDX (`.mdx`), or Markdoc (`.mdoc`)
- `'data'` - for data-only formats like JSON (`.json`) or YAML (`.yaml`)

:::tip
This means collections **cannot** store a mix of content and data formats. You must split these entries into separate collections by type.
:::

#### `schema`

**Type:** `TSchema extends ZodType`

`schema` is an optional Zod object to configure the type and shape of document frontmatter for a collection. Each value must use [a Zod validator](https://github.com/colinhacks/zod).

[See the `Content Collection` guide](/en/guides/content-collections/#defining-a-collection-schema) for example usage.

### `reference()`

**Type:** `(collection: string) => ZodEffects<ZodString, { collection, id: string } | { collection, slug: string }>`

The `reference()` function is used in the content config to define a relationship, or "reference," from one collection to another. This accepts a collection name and validates the entry identifier(s) specified in your content frontmatter or data file.

This example defines references from a blog author to the `authors` collection and an array of related posts to the same `blog` collection:

```ts
import { defineCollection, reference, z } from 'astro:content';

const blog = defineCollection({
  type: 'content',
  schema: z.object({
    // Reference a single author from the `authors` collection by `id`
    author: reference('authors'),
    // Reference an array of related posts from the `blog` collection by `slug`
    relatedPosts: z.array(reference('blog')),
  })
});

const authors = defineCollection({
  type: 'data',
  schema: z.object({ /* ... */ })
});

export const collections = { blog, authors };
```

[See the `Content Collection` guide](/en/guides/content-collections/#defining-collection-references) for example usage.

### `getCollection()`

**Type:** `(collection: string, filter?: (entry: CollectionEntry<collection>) => boolean) => CollectionEntry<collection>[]`

`getCollection()` is a function that retrieves a list of content collection entries by collection name.

It returns all items in the collection by default, and accepts an optional `filter` function to narrow by entry properties. This allows you to query for only some items in a collection based on `id`, `slug`, or frontmatter values via the `data` object.

```astro
---
import { getCollection } from 'astro:content';

// Get all `src/content/blog/` entries
const allBlogPosts = await getCollection('blog');

// Only return posts with `draft: true` in the frontmatter
const draftBlogPosts = await getCollection('blog', ({ data }) => {
  return data.draft === true;
});
---
```

[See the `Content Collection` guide](/en/guides/content-collections/#querying-collections) for example usage.

### `getEntry()`

<p><Since v="2.5.0" /></p>

**Types:**

- `(collection: string, contentSlugOrDataId: string) => CollectionEntry<collection>`
- `({ collection: string, id: string }) => CollectionEntry<collection>`
- `({ collection: string, slug: string }) => CollectionEntry<collection>`

`getEntry()` is a function that retrieves a single collection entry by collection name and either the entry `id` (for `type: 'data'` collections) or entry `slug` (for `type: 'content'` collections). `getEntry()` can also be used to get referenced entries to access the `data`, `body`, or `render()` properties:

```astro
---
import { getEntry } from 'astro:content';

// Get `src/content/blog/enterprise.md`
const enterprisePost = await getEntry('blog', 'enterprise');

// Get `src/content/captains/picard.yaml`
const picardProfile = await getEntry('captains', 'picard');

// Get the profile referenced by `data.captain`
const enterpriseCaptainProfile = await getEntry(enterprisePost.data.captain);
---
```

See the `Content Collections` guide for examples of [querying collection entries](/en/guides/content-collections/#querying-collections).

### `getEntries()`

<p><Since v="2.5.0" /></p>

**Types:**

- `(Array<{ collection: string, id: string }>) => Array<CollectionEntry<collection>>`
- `(Array<{ collection: string, slug: string }>) => Array<CollectionEntry<collection>>`

`getEntries()` is a function that retrieves multiple collection entries from the same collection. This is useful for [returning an array of referenced entries](/en/guides/content-collections/#defining-collection-references) to access their associated `data`, `body`, and `render()` properties.

```astro
---
import { getEntries } from 'astro:content';

const enterprisePost = await getEntry('blog', 'enterprise');

// Get related posts referenced by `data.relatedPosts`
const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts);
---
```

### `getEntryBySlug()`

**Type:** `(collection: string, slug: string) => CollectionEntry<collection>`

:::caution[Deprecated]
Use the [`getEntry()` function](#getentry) to query content entries. This accepts the same arguments as `getEntryBySlug()`, and supports querying by `id` for JSON or YAML collections.
:::

`getEntryBySlug()` is a function that retrieves a single collection entry by collection name and entry `slug`.


```astro
---
import { getEntryBySlug } from 'astro:content';

const enterprise = await getEntryBySlug('blog', 'enterprise');
---
```

[See the `Content Collection` guide](/en/guides/content-collections/#querying-collections) for example usage.

### Collection Entry Type

Query functions including [`getCollection()`](#getcollection), [`getEntry()`](#getentry), and [`getEntries()`](#getentries) each return entries with the `CollectionEntry` type. This type is available as a utility from `astro:content`:

```ts
import type { CollectionEntry } from 'astro:content';
```

The `CollectionEntry<TCollectionName>` type is an object with the following values. `TCollectionName` is the name of the collection you're querying (e.g. `CollectionEntry<'blog'>`).

#### `id`

**Available for:** `type: 'content'` and `type: 'data'` collections  
**Example Types:**
  - content collections: `'entry-1.md' | 'entry-2.md' | ...`
  - data collections: `'author-1' | 'author-2' | ...`

A unique ID using the file path relative to `src/content/[collection]`. Enumerates all possible string values based on the collection entry file paths. Note that collections [defined as `type: 'content'`](#type) include the file extension in their ID, while collections defined as `type: 'data'` do not.

#### `collection`

**Available for:** `type: 'content'` and `type: 'data'` collections  
**Example Type:** `'blog' | 'authors' | ...`

The name of a top-level folder under `src/content/` in which entries are located. This is the name used to reference the collection in your schema, and in querying functions.

#### `data`

**Available for:** `type: 'content'` and `type: 'data'` collections  
**Type:** `CollectionSchema<TCollectionName>`

An object of frontmatter properties inferred from your collection schema ([see `defineCollection()` reference](#definecollection)). Defaults to `any` if no schema is configured.

#### `slug`

**Available for:** `type: 'content'` collections only  
**Example Type:** `'entry-1' | 'entry-2' | ...`

A URL-ready slug for Markdown or MDX documents. Defaults to the `id` without the file extension, but can be overridden by setting [the `slug` property](/en/guides/content-collections/#defining-custom-slugs) in a file's frontmatter.

#### `body`

**Available for:** `type: 'content'` collections only  
**Type:** `string`

A string containing the raw, uncompiled body of the Markdown or MDX document.

#### `render()`

**Available for:** `type: 'content'` collections only  
**Type:** `() => Promise<RenderedEntry>`

A function to compile a given Markdown or MDX document for rendering. This returns the following properties:

- `<Content />` - A component used to render the document's contents in an Astro file.
- `headings` - A generated list of headings, [mirroring Astro's `getHeadings()` utility](/en/guides/markdown-content/#exported-properties) on Markdown and MDX imports.
- `remarkPluginFrontmatter ` - The modified frontmatter object after any [remark or rehype plugins have been applied](/en/guides/markdown-content/#modifying-frontmatter-programmatically). Set to type `any`.

```astro
---
import { getEntryBySlug } from 'astro:content';
const entry = await getEntryBySlug('blog', 'entry-1');

const { Content, headings, remarkPluginFrontmatter } = await entry.render();
---
```

[See the `Content Collection` guide](/en/guides/content-collections/#rendering-content-to-html) for example usage.

### Other Content Collection Types

The `astro:content` module also exports the following types for use in your Astro project:

#### `CollectionKey`

A string union of all collection names defined in your `src/content/config.*` file. This type can be useful when defining a generic function that accepts any collection name.

```ts
import type { CollectionKey, getCollection } from 'astro:content';

async function getCollection(collection: CollectionKey) {
  return getCollection(collection);
}
```

#### `ContentCollectionKey`

A string union of all the names of `type: 'content'` collections defined in your `src/content/config.*` file.

#### `DataCollectionKey`

A string union of all the names of `type: 'data'` collection defined in your `src/content/config.*` file.

#### `SchemaContext`

The `context` object that `defineCollection` uses for the function shape of `schema`. This type can be useful when building reusable schemas for multiple collections.

This includes the following property:

- `image` - The `image()` schema helper that allows you [to use local images in Content Collections](/en/guides/images/#images-in-content-collections)

```ts
import type { SchemaContext } from 'astro:content';

export const imageSchema = ({ image }: SchemaContext) =>
    z.object({
        image: image(),
        description: z.string().optional(),
    });

const blog = defineCollection({
  type: 'content',
  schema: ({ image }) => z.object({
    title: z.string(),
    permalink: z.string().optional(),
    image: imageSchema({ image })
  }),
});
```

## Middleware (`astro:middleware`)

<p><Since v="2.6.0" /></p>

Middleware allows you to intercept requests and responses and inject behaviors dynamically every time a page or endpoint is about to be rendered. For features and usage examples, [see our middleware guide](/en/guides/middleware/).

### `onRequest()`

A required exported function from `src/middleware.js` that will be called before rendering every page or API route. It accepts two optional arguments: [context](#contextlocals) and [next()](#next). `onRequest()` must return a `Response`: either directly, or by calling `next()`.

```js title="src/middleware.js"
export function onRequest (context, next) {
    // intercept response data from a request
    // optionally, transform the response
    // return a Response directly, or the result of calling `next()`
    return next();
};
```

### `next()`

A function that intercepts (reads and modifies) the `Response` of a `Request` or calls the "next" middleware in the chain and returns a `Response`. For example, this function could modify the HTML body of a response.

This is an optional argument of `onRequest()`, and may provide the required `Response` returned by the middleware.


### `sequence()`

A function that accepts middleware functions as arguments, and will execute them in the order in which they are passed. 

```js title="src/middleware.js"
import { sequence } from "astro:middleware";

async function validation(_, next) {...}
async function auth(_, next) {...}
async function greeting(_, next) {...}

export const onRequest = sequence(validation, auth, greeting);
```

### `createContext()`

A low-level API to create an [`APIContext`](#endpoint-context)to be passed to an Astro middleware `onRequest()` function.

This function can be used by integrations/adapters to programmatically execute the Astro middleware.

### `trySerializeLocals()`

A low-level API that takes in any value and tries to return a serialized version (a string) of it. If the value cannot be serialized, the function will throw a runtime error.


## Built-in Components

Astro includes several built-in components for you to use in your projects. All built-in components are available in `.astro` files via `import {} from 'astro:components';`.

### `<Code />`

```astro 'theme="dark-plus"' /wrap\b/ /(inline) \/>/
---
import { Code } from 'astro:components';
---
<!-- Syntax highlight some JavaScript code. -->
<Code code={`const foo = 'bar';`} lang="js" />
<!-- Optional: Customize your theme. -->
<Code code={`const foo = 'bar';`} lang="js" theme="dark-plus" />
<!-- Optional: Enable word wrapping. -->
<Code code={`const foo = 'bar';`} lang="js" wrap />
<!-- Optional: Output inline code. -->
<p>
  <Code code={`const foo = 'bar';`} lang="js" inline />
  will be rendered inline.
</p>
```

This component provides syntax highlighting for code blocks at build time (no client-side JavaScript included). The component is powered internally by Shiki and it supports all popular [themes](https://shiki.style/themes) and [languages](https://shiki.style/languages). Plus, you can add your custom themes and languages by passing them to `theme` and `lang` respectively.

### `<Fragment />`

A component used with [`set:*` directives](/en/reference/directives-reference/#sethtml) to render HTML content without any additional wrapping elements:

```astro title="src/components/SetHtml.astro" "Fragment"
---
const htmlString = '<p>Raw HTML content</p>';
---
<Fragment set:html={htmlString} />
```

See more about [using fragments](/en/basics/astro-syntax/#fragments) in Astro syntax.

### `<Prism />`

To use the `Prism` highlighter component, first **install** the `@astrojs/prism` package:

<PackageManagerTabs>
  <Fragment slot="npm">
  ```shell
  npm install @astrojs/prism
  ```
  </Fragment>
  <Fragment slot="pnpm">
  ```shell
  pnpm add @astrojs/prism
  ```
  </Fragment>
  <Fragment slot="yarn">
  ```shell
  yarn add @astrojs/prism
  ```
  </Fragment>
</PackageManagerTabs>

```astro
---
import { Prism } from '@astrojs/prism';
---
<Prism lang="js" code={`const foo = 'bar';`} />
```

This component provides language-specific syntax highlighting for code blocks by applying Prism's CSS classes. Note that **you need to provide a Prism CSS stylesheet** (or bring your own) for syntax highlighting to appear! See the [Prism configuration section](/en/guides/markdown-content/#prism-configuration) for more details.

See the [list of languages supported by Prism](https://prismjs.com/#supported-languages) where you can find a language’s corresponding alias. And, you can also display your Astro code blocks with `lang="astro"`!

### `<Image />`

```astro title="src/components/MyComponent.astro"
---
// import the Image component and the image
import { Image } from 'astro:assets';
import myImage from "../assets/my_image.png"; // Image is 1600x900
---

<!-- `alt` is mandatory on the Image component -->
<Image src={myImage} alt="A description of my image." />
```

```html
<!-- Output -->
<!-- Image is optimized, proper attributes are enforced -->
<img
  src="/_astro/my_image.hash.webp"
  width="1600"
  height="900"
  decoding="async"
  loading="lazy"
  alt="A description of my image."
/>
```
#### Properties

- src (required)
- alt (required)
- width and height (required for `public/` and remote images)
- format
- quality
- densities
- widths

In addition to the properties above, the `<Image />` component accepts all properties accepted by the HTML `<img>` tag.

See more in the [Images Guide](/en/guides/images/#image--astroassets).

### `<Picture />`

<p><Since v="3.3.0" /></p>

Use the built-in `<Picture />` Astro component to display a responsive image with multiple formats and/or sizes.

```astro title="src/pages/index.astro"
---
import { Picture } from 'astro:assets';
import myImage from "../assets/my_image.png"; // Image is 1600x900
---

<!-- `alt` is mandatory on the Picture component -->
<Picture src={myImage} formats={['avif', 'webp']} alt="A description of my image." />
```

```html
<!-- Output -->
<picture>
  <source srcset="/_astro/my_image.hash.avif" type="image/avif" />
  <source srcset="/_astro/my_image.hash.webp" type="image/webp" />
  <img
    src="/_astro/my_image.hash.png"
    width="1600"
    height="900"
    decoding="async"
    loading="lazy"
    alt="A description of my image."
  />
</picture>
```

See more in the [Images Guide](/en/guides/images/#picture-).

#### Properties

`<Picture />` accepts all the properties of the `<Image />` component, plus the following:

##### `formats`

An array of image formats to use for the `<source>` tags. By default, this is set to `['webp']`.

##### `fallbackFormat`

Format to use as a fallback value for the `<img>` tag. Defaults to `.png` for static images, `.gif` for animated images, and `.svg` for SVG files.

##### `pictureAttributes`

An object of attributes to be added to the `<picture>` tag. Use this property to apply attributes to the outer `<picture>` element itself. Attributes applied to the `<Picture />` component directly will apply to the inner `<img>` element, except for those used for image transformation.


### `<Content />`

A generic component used to render the content of a [content collection entry](/en/guides/content-collections/#what-are-content-collections).

First, query one or more entries using `getCollection()` or `getEntry()`. Then, the `entry.render()` function can return the `<Content />` component for use in a `.astro` file template.

```astro title="src/pages/render-example.astro" {4, 7}
---
import { getEntry } from 'astro:content';
const entry = await getEntry('blog', 'post-1');
const { Content } = await entry.render();
---
<p>Published on: {entry.data.published.toDateString()}</p>
<Content />
```

### `<ViewTransitions />`

Opt in to using view transitions on individual pages by importing and adding the `<ViewTransitions />` routing component to `<head>` on every desired page.

```astro title="src/pages/index.astro" ins={2,7}
---
import { ViewTransitions } from 'astro:transitions';
---
<html lang="en">
  <head>
    <title>My Homepage</title>
    <ViewTransitions />
  </head>
  <body>
    <h1>Welcome to my website!</h1>
  </body>
</html>
```

See more about how to [control the router](/en/guides/view-transitions/#router-control) and [add transition directives](/en/guides/view-transitions/#transition-directives) to page elements and components.

### `<Debug />`

```astro
---
import { Debug } from 'astro:components';
const serverObject = {
  a: 0,
  b: "string",
  c: {
    nested: "object"
  }
}
---
<Debug {serverObject} />
```

This component provides a way to inspect values on the client-side, without any JavaScript.


[canonical]: https://en.wikipedia.org/wiki/Canonical_link_element
